package org.demo.warehouse.controller;

import io.netty.handler.codec.http.HttpHeaders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yeauty.annotation.*;
import org.yeauty.pojo.Session;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zgc
 * @since 2019/11/12
 */
@ServerEndpoint(port = 9091)
@Component
@Slf4j
public class MyWebSocket {

    private static Set<Session> sessions = ConcurrentHashMap.newKeySet();

    @OnOpen
    public void onOpen(Session session, HttpHeaders headers) throws IOException {
        sessions.add(session);
        log.info("管理员：{}已进入");
    }

    @OnClose
    public void onClose(Session session) throws IOException {
        sessions.remove(session);
        log.info("管理员：{}已退出");
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        log.error("{}",throwable);
    }

    @OnMessage
    public void OnMessage(Session session, String message) {
        log.info(message);
        session.sendText("Hello {}! --from Netty");
    }

    public static void sendMessage(String message){
        sessions.forEach(session -> session.sendText(message));
    }
}
